package com.zjnx.train.action.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.TableConstants;
import org.extremecomponents.table.limit.Limit;
import org.extremecomponents.table.limit.LimitFactory;
import org.extremecomponents.table.limit.TableLimit;
import org.extremecomponents.table.limit.TableLimitFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.zjnx.train.entity.User;
import com.zjnx.train.service.UserService;

/**
 * @author foo
 * @email foo@zjnx.com
 * @description: 用户管理
 */
public class UserMgtAction extends ActionSupport implements ServletRequestAware {

    private static final long serialVersionUID = 1L;
    public static final int DEFAULT_ROWS_DISPLAYED = 10;
    private UserService userService;
    private User user;
    private HttpServletRequest request;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String index() throws Exception {
        request.setAttribute(TableConstants.TOTAL_ROWS, 0);
        return SUCCESS;
    }

    public String list() throws Exception {
        Context context = new HttpServletRequestContext(request);
        LimitFactory limitFactory = new TableLimitFactory(context);
        Limit limit = new TableLimit(limitFactory);

        // String queryString = "from User where name=? and gender=?";
        // List<User> users = userService.listAll(limit, queryString, user.getName(), user.getGender());

        List<User> users = userService.listAll(limit, user);

        request.setAttribute("users", users);
        request.setAttribute(TableConstants.TOTAL_ROWS, limit.getTotalRows());
        return SUCCESS;
    }

    @Override
    public String input() throws Exception {
        if (user != null && user.getId() != null) {
            user = userService.findByKey(user.getId());
        }
        return INPUT;
    }

    public String save() throws Exception {
        if (user == null) {
            return execute();
        }
        if (user.getId() == null) {
            userService.save(user);
        } else {
            userService.update(user);
        }
        return "redirect";
    }

    public String delete() throws Exception {
        if (user != null && user.getId() != null) {
            userService.delete(user.getId());
        }
        return "redirect";
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

}
